package com.atguitu.campus.renwendemo.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * HTTP 工具类 - 支持 JSON 参数传递
 * 基于 OkHttp 实现，提供 GET、POST、PUT、DELETE 等常用 HTTP 请求方法
 */
public class HttpUtils {
    private static final OkHttpClient client;
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    // 初始化 OkHttpClient
    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();
    }

    // 私有化构造函数，防止实例化
    private HttpUtils() {}

    /**
     * 发送 GET 请求
     * @param url 请求 URL
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String get(String url) throws IOException {
        return get(url, new HashMap<>(), new HashMap<>());
    }

    /**
     * 发送 GET 请求（带参数）
     * @param url 请求 URL
     * @param params 查询参数
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String get(String url, Map<String, String> params) throws IOException {
        return get(url, params, new HashMap<>());
    }

    /**
     * 发送 GET 请求（带参数和请求头）
     * @param url 请求 URL
     * @param params 查询参数
     * @param headers 请求头
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String get(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
        // 构建带参数的 URL
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> param : params.entrySet()) {
                urlBuilder.addQueryParameter(param.getKey(), param.getValue());
            }
        }
        String fullUrl = urlBuilder.build().toString();

        Request.Builder requestBuilder = new Request.Builder()
                .url(fullUrl)
                .get();

        // 添加请求头
        addHeaders(requestBuilder, headers);

        try (Response response = client.newCall(requestBuilder.build()).execute()) {
            return handleResponse(response);
        }
    }

    /**
     * 发送 POST 请求（JSON 参数）
     * @param url 请求 URL
     * @param json JSON 格式的请求体
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String postJson(String url, String json) throws IOException {
        return postJson(url, json, new HashMap<>());
    }

    /**
     * 发送 POST 请求（JSON 参数和请求头）
     * @param url 请求 URL
     * @param json JSON 格式的请求体
     * @param headers 请求头
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String postJson(String url, String json, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        return executeRequest(url, "POST", body, headers);
    }

    /**
     * 发送 PUT 请求（JSON 参数）
     * @param url 请求 URL
     * @param json JSON 格式的请求体
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String putJson(String url, String json) throws IOException {
        return putJson(url, json, new HashMap<>());
    }

    /**
     * 发送 PUT 请求（JSON 参数和请求头）
     * @param url 请求 URL
     * @param json JSON 格式的请求体
     * @param headers 请求头
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String putJson(String url, String json, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        return executeRequest(url, "PUT", body, headers);
    }

    /**
     * 发送 DELETE 请求
     * @param url 请求 URL
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String delete(String url) throws IOException {
        return delete(url, new HashMap<>());
    }

    /**
     * 发送 DELETE 请求（带请求头）
     * @param url 请求 URL
     * @param headers 请求头
     * @return 响应结果
     * @throws IOException 网络异常
     */
    public static String delete(String url, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .delete();

        // 添加请求头
        addHeaders(requestBuilder, headers);

        try (Response response = client.newCall(requestBuilder.build()).execute()) {
            return handleResponse(response);
        }
    }

    // 执行 HTTP 请求的通用方法
    private static String executeRequest(String url, String method, RequestBody body, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder()
                .url(url);

        // 设置请求方法和请求体
        switch (method.toUpperCase()) {
            case "POST":
                requestBuilder.post(body);
                break;
            case "PUT":
                requestBuilder.put(body);
                break;
            case "DELETE":
                requestBuilder.delete(body);
                break;
            default:
                throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }

        // 添加请求头
        addHeaders(requestBuilder, headers);

        try (Response response = client.newCall(requestBuilder.build()).execute()) {
            return handleResponse(response);
        }
    }

    // 添加请求头
    private static void addHeaders(Request.Builder requestBuilder, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                requestBuilder.addHeader(header.getKey(), header.getValue());
            }
        }
    }

    // 处理响应结果
    private static String handleResponse(Response response) throws IOException {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected response code: " + response.code() + ", body: " +
                    (response.body() != null ? response.body().string() : "null"));
        }
        return response.body() != null ? response.body().string() : "";
    }

    // 主方法示例
    public static void main(String[] args) {
        try {


            // POST JSON 请求示例
//            JSONObject jsonBody = new JSONObject();
//            jsonBody.put("model","lite");
//            jsonBody.put("user","user_1234567876");
//            JSONArray messageArr = new JSONArray();
//            JSONObject message = new JSONObject();
//            message.put("role","system");
//            message.put("content","你是知识渊博的助理");
//            JSONObject user = new JSONObject();
//            messageArr.add(message);
//            user.put("role","user");
//            user.put("content","你好，讯飞星火");
//            messageArr.add(user);


//            jsonBody.put("messages",messageArr);

//            Map<String, String> headers = new HashMap<>();
//            headers.put("Authorization","Bearer elumSDRdJlnLalmRlxnK:dpRJBCFVdTBnBKJKeGIz");
//            headers.put("Content-Type","application/json");
//            String postResponse = HttpUtils.postJson("https://spark-api-open.xf-yun.com/v1/chat/completions", jsonBody.toJSONString(),headers);
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type","application/json");
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("filePath","home/upload/7.jpg");
            String postResponse = HttpUtils.postJson("http://127.0.0.1:5000/data", jsonBody.toJSONString(),headers);

            System.out.println("POST Response: " + postResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}